package com.iot.ic.base;

import com.iot.ic.common.CustomException;
import com.iot.ic.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@Controller
public class BaseController {

	private Logger logger = LoggerFactory.getLogger(BaseController.class);

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Response runtimeExceptionHandler(Exception runtimeException) {
		logger.error(runtimeException.getLocalizedMessage());
		Response response = new Response();
		if (runtimeException instanceof CustomException) {
			CustomException customException=(CustomException)runtimeException;
			response=new Response(customException);
		} else if(runtimeException instanceof MethodArgumentNotValidException){
			BindingResult bindingResult=((MethodArgumentNotValidException)runtimeException).getBindingResult();
			response=new Response(bindingResult);
		}else if(runtimeException instanceof BindException){
			BindingResult bindingResult=((BindException)runtimeException).getBindingResult();
			response=new Response(bindingResult);
		}else {
			response.setStatus("error");
			response.setDescription(runtimeException.getClass().getSimpleName() + ":" + runtimeException.getMessage());
			//response.setExceptionType(runtimeException.getClass().getSimpleName() + ":" + runtimeException.getMessage());
		}
		return response;
	}

	/**
	 * @Description: 判断是否是ajax请求 @author @param: @param
	 * 如果值为XMLHttpRequest则为异步请求，如果为null则为同步
	 * request @param: @return @return: boolean @throws
	 */
	protected boolean isAjaxCall(HttpServletRequest request) {
		return ("XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
	}


}
